package com.qiaofang.applet.service.other.service.impl;

import com.qiaofang.applet.common.client.weixin.WxService;
import com.qiaofang.applet.common.client.weixin.model.WxProperties;
import com.qiaofang.applet.common.context.QfContextHolder;
import com.qiaofang.applet.common.exception.BusinessException;
import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.service.CorporationService;
import com.qiaofang.applet.service.other.service.WxaUnlimitQrCodeService;
import com.qiaofang.applet.service.other.service.dto.WxaUnlimitQrCodeDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

/**
 * 小程序二维码
 * @author junze.liu
 */
@Slf4j
@Service
public class WxaUnlimitQrCodeServiceImpl implements WxaUnlimitQrCodeService {

    @Autowired
    private CorporationService corporationService;

    @Autowired
    private WxService wxService;

    @Override
    public String createMiniQrCode(WxaUnlimitQrCodeDto dto) {
        String corporationCode = QfContextHolder.getContext().getCorporationCode();
        if(StringUtils.isBlank(corporationCode)) {
            log.error("创建小程序二维码，未获取到集团code");
            throw new BusinessException("创建小程序二维码，未获取到集团code");
        }
        //获取小程序appid
        Corporation corporation = corporationService.getCorporationByCorporationCode(corporationCode);
        if (StringUtils.isEmpty(corporation.getAuthAppId()) || StringUtils.isEmpty(corporation.getAuthAppSecret())){
            throw new BusinessException("小程序appID或secret未配置");
        }
        WxProperties config = new WxProperties();
        config.setAppId(corporation.getAuthAppId());
        config.setAppSecret(corporation.getAuthAppSecret());
        //小程序端获取二维码
        return getMiniQrCode(dto.getPage(), "sid=" + dto.getSid(), config);

    }

    /**
     * 小程序端获取小程序二维码
     * @param
     * @param config
     * @return
     */
    private String getMiniQrCode(String page, String scene, WxProperties config) {
        byte[] result = wxService.getWxaCodeUnlimit(page, scene, config);
        String strBase64 = new BASE64Encoder().encode(result);
        return strBase64.replaceAll("\r\n","");
    }
}
